package com.znsd.exam.controllor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.znsd.entitys.ExamSubjectMiddleInfo;
import com.znsd.entitys.Subjectinfo;
import com.znsd.exam.service.ExamSubjectMiddleService;
import com.znsd.exam.service.SubjectService;
import com.znsd.utils.FormatUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;

@RestController
@RequestMapping("/upload")
@Scope("prototype")
public class ImportAndExportController {
	
	@Autowired
	private ExamSubjectMiddleService esms;
	@Autowired
	private SubjectService subjectService;

	@RequestMapping(value = "/exportWord")
	public void exportWord(Integer studentId,Integer examPaperId,HttpSession session, HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		String realPath = session.getServletContext().getRealPath("/");
		realPath = realPath.replaceAll("/", "\\\\");

		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		Map<String, Object> dataMap = new HashMap<>();
		List<Map<String, Object>> table2 = new ArrayList<>();
		List<Map<String, Object>> urlList = new ArrayList<>();
		Map<String, String> checkUrl = new HashMap<>();

		/*
		 * String url = request.getContextPath();
		 * System.out.println(UploadController.class.getResource("/"));
		 * System.out.println(url);
		 */
		String path = session.getServletContext().getRealPath("/");
		String allUrl = "";
		int index = 1;
		allUrl += FormatUtil.getImageStr("F:\\TomcatWorkSpace\\WX\\my1\\img\\h1.png");
		String filename1 = "F:\\TomcatWorkSpace\\WX\\my1\\img\\h1.png";// 文件名
		String[] strArray = filename1.split("\\.");
		String s = "rId4";
		int suffixIndex = strArray.length - 1;
		String contentType = strArray[suffixIndex];

		String fileName = filename1;
		String fileTyle = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		List<ExamSubjectMiddleInfo> list = esms.getOne(examPaperId);
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map1 = new HashMap<>();

			List<String> list1 = new ArrayList<>();
			int temp = index + 3;

			Map<String, Object> map = new HashMap<>();
			String mapPath = realPath + "\\uploads\\h1.png";

			int index2 = -1;
			for (String check : checkUrl.keySet()) {
				if (check.equals(mapPath)) {
					index2 = 1;
					list1.add(checkUrl.get(check));
					map1.put("urls", list1); // 图片
				}
			}

			if (index2 == -1) {
				String rid = "rId" + temp;
				list1.add(rid);
				map1.put("urls", list1); // 图片

				urlList.add(map);
				checkUrl.put(mapPath, rid);

				fileTyle = mapPath.substring(mapPath.lastIndexOf("."), mapPath.length());
				strArray = mapPath.split("\\.");
				suffixIndex = strArray.length - 1;
				contentType = strArray[suffixIndex];
				map.put("name", "/word/media/image" + index + fileTyle);
				map.put("contentType", "image/" + contentType);
				map.put("value", FormatUtil.getImageStr(mapPath));
				index++;
			
			}

			if (i == 1) {
				for (int j = 0; j < 2; j++) {
					mapPath = realPath + "\\uploads\\1.jpeg";
					int index3 = -1;
					for (String check : checkUrl.keySet()) {
						if (check.equals(mapPath)) {
							index3 = 1;
							list1.add(checkUrl.get(check));
							map1.put("urls", list1); // 图片
						}
					}
					if (index3 == -1) {
						String rid = "rId" + temp;
						list1.add(rid);
						map1.put("urls", list1); // 图片
						urlList.add(map);
						checkUrl.put(mapPath, rid);
						fileTyle = mapPath.substring(mapPath.lastIndexOf("."), mapPath.length());
						strArray = mapPath.split("\\.");
						suffixIndex = strArray.length - 1;
						contentType = strArray[suffixIndex];
						map.put("name", "/word/media/image" + index + fileTyle);
						map.put("contentType", "image/" + contentType);
						map.put("value", FormatUtil.getImageStr(mapPath));
						index++;
					}
				}
				/*
				 * Map<String,Object> map2 = new HashMap<>(); fileTyle =
				 * mapPath.substring(mapPath.lastIndexOf("."), mapPath.length()); strArray =
				 * mapPath.split("\\."); suffixIndex = strArray.length - 1; contentType =
				 * strArray[suffixIndex]; map2.put("name", "/word/media/image" + index +
				 * fileTyle); map2.put("contentType", "image/"+contentType); map2.put("value",
				 * getImageStr(mapPath)); urlList.add(map2); index++;
				 */
			}

//			topic.getUrl().add(getImageStr(path+"img/h1.png"));
			Subjectinfo subjectinfo = subjectService.getSubjectWithId(list.get(i).getSubjectId());
			map1.put("point", subjectinfo.getChapter().getSpecialty_name()); // 技能点
			map1.put("title",subjectinfo.getSubjectName()); // 题干
			map1.put("analysis", subjectinfo.getJiexi()); // 解析
			if(subjectinfo.getSubjectType()==1) {
				map1.put("type", "单选"); // 题目类型
			}else {
				map1.put("type", "多选"); // 题目类型
			}
			List<String> options = new ArrayList<>();
			options.add("A:"+subjectinfo.getOptionA());
			options.add("B:"+subjectinfo.getOptionB());
			options.add("C:"+subjectinfo.getOptionC());
			options.add("D:"+subjectinfo.getOptionD());
			map1.put("options", options);
			map1.put("rightOption", subjectinfo.getRightResult());
			table2.add(map1);
		}

		/*
		 * for (int i = 0; i < 91; i++) { Topic topic = new Topic(); // topic 这个类只是演示用的
		 * 你要根据自己的业务具体的写属性
		 * 
		 * topic.getUrl().add("1"); String mapPath = ""; if (i == 20) {
		 * topic.getUrl().add("2"); Map<String, Object> map = new HashMap<>(); mapPath =
		 * "F:\\TomcatWorkSpace\\WX\\demo7\\img\\1.jpeg"; strArray =
		 * mapPath.split("\\."); suffixIndex = strArray.length - 1; contentType =
		 * strArray[suffixIndex]; map.put("id", "" + index); map.put("name",
		 * "/word/media/image" + index + fileTyle); map.put("contentType",
		 * "image/"+contentType); map.put("value", getImageStr(mapPath));
		 * urlList.add(map); } mapPath = "F:\\TomcatWorkSpace\\WX\\demo7\\img\\h1.png";
		 * Map<String, Object> map = new HashMap<>(); strArray = mapPath.split("\\.");
		 * suffixIndex = strArray.length - 1; contentType = strArray[suffixIndex];
		 * map.put("name", "/word/media/image" + index + fileTyle);
		 * map.put("contentType", "image/"+contentType); map.put("value",
		 * getImageStr(mapPath)); urlList.add(map); topic.getUrl().add("rId" + index+3);
		 * index++; // topic.getUrl().add(getImageStr(path+"img/h1.png"));
		 * topic.setAnalysis("解析" + i); // topic.setAnalysis(new PictureRenderData(100,
		 * 120, "img/1.jepg")); topic.setType(i); topic.setTitle(
		 * "titlediushfuihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
		 * + i); table2.add(topic); }
		 */
		dataMap.put("table2", table2);
		dataMap.put("path2", urlList);
		// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
		// 这里我们的模板是放在com.havenliu.document.template包下面
		configuration.setClassForTemplateLoading(this.getClass(), "/model/"); // 这个路径自己随便建一个就行了
		Template t = null;
		Writer out = null;
		File outFile = null;
		try {
			t = configuration.getTemplate("word.ftl");
			String name = "temp" + (int) (Math.random() * 100000) + ".docx";
			outFile = new File(name);
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
			t.process(dataMap, out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally { // finally下面的代码很重要 否则的话你导不出word 必须flush close 一下才行
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		// 下面这些代码是为了你的 导出做准备的
		request.setCharacterEncoding("UTF-8");
		File file = null;
		InputStream fin = null;
		ServletOutputStream out1 = null;
		try {
			fin = new FileInputStream(outFile);
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/msword");
			// 设置浏览器以下载的方式处理该文件默认名为Exhibition.doc
			String fileName2 = URLEncoder.encode("export-Word-name" + ".docx", "utf-8");
			response.setHeader("content-disposition", "attachment;filename=" + fileName2);
			out1 = response.getOutputStream();
			byte[] buffer = new byte[1024]; // 缓冲区
			int bytesToRead = -1;
			// 通过循环将读入的Word文件的内容输出到浏览器中
			while ((bytesToRead = fin.read(buffer)) != -1) {
				out1.write(buffer, 0, bytesToRead);
			}
		} finally {
			if (fin != null)
				fin.close();
			if (out1 != null)
				out1.close();
			if (outFile != null)
				outFile.delete(); // 删除临时文件
		}
	}

	/**
	 * 描述：通过传统方式form表单提交方式导入excel文件
	 * 
	 * @param request
	 * @throws Exception @RequestParam("file") MultipartFile[] files,
	 */
	/*
	 * @RequestMapping(value = "excel", method = { RequestMethod.GET,
	 * RequestMethod.POST }) public String uploadExcel(ServletRequest request,
	 * MultipartFile file) throws Exception { InputStream in = null;
	 * List<List<Object>> listob = null; if (file.isEmpty()) { throw new
	 * Exception("文件不存在！"); }
	 * 
	 * in = file.getInputStream(); listob = new
	 * ImportExcelUtil().getBankListByExcel(in, file.getOriginalFilename());
	 * in.close();
	 * 
	 * // 该处可调用service相应方法进行数据保存到数据库中，现只对数据输出 for (int i = 0; i < listob.size();
	 * i++) { List<Object> lo = listob.get(i); InfoVo vo = new InfoVo();
	 * vo.setCode(String.valueOf(lo.get(0))); vo.setName(String.valueOf(lo.get(1)));
	 * vo.setDate(String.valueOf(lo.get(2)));
	 * vo.setMoney(String.valueOf(lo.get(3)));
	 * 
	 * System.out.println("打印信息-->机构:" + vo.getCode() + " 名称：" + vo.getName() +
	 * " 时间：" + vo.getDate() + " 资产：" + vo.getMoney()); } return "result"; }
	 */

}
